package com.open.api.peekapi.services;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.open.api.peekapi.bean.ApiItem;
import com.open.api.peekapi.dao.ApiItemDao;
import com.open.api.peekapi.util.HelpMe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by mengdexuan on 2017/6/20 18:25.
 */
@Service
public class ApiItemServices {

	@Autowired
	ApiItemDao apiItemDao;

	public List<ApiItem> firstLevelItem(){

		List<ApiItem> list = apiItemDao.findByParentIdAndShowFlagOrderByCreateTime(null,1);

		return list;
	}

	public List<ApiItem> firstLevelItemAll(){

		List<ApiItem> list = apiItemDao.findByParentIdOrderByCreateTime(null);

		return list;
	}

	public List<ApiItem> secondLevelByFirstLevelId(String firstLevelId){

		List<ApiItem> list = apiItemDao.findByParentIdOrderByCreateTime(firstLevelId);

		return list;
	}



	public Boolean changeStatus(String id){
		ApiItem one = apiItemDao.getOne(id);
		int temp = 0;
		if (one.getShowFlag()==0){
			temp = 1;
		}
		one.setShowFlag(temp);
		apiItemDao.save(one);

		return true;
	}



	public Boolean del(String id){

		List<Record> list = Db.find("select id from api_item where parent_id = ?", new Object[]{id});
		if (HelpMe.isNotNull(list))return false;

		apiItemDao.delete(id);

		return true;
	}

	public Boolean del2(String id){

		List<Record> list = Db.find("select id from api_item_data where item_id = ?", new Object[]{id});
		if (HelpMe.isNotNull(list))return false;

		apiItemDao.delete(id);

		return true;
	}


	public ApiItem add(ApiItem apiItem){
		ApiItem result = null;
		if (apiItem.getId()==null){
			apiItem.setCreateTime(new Date());
			apiItem.setId(HelpMe.uuid());
			apiItem.setShowFlag(1);
			result = apiItemDao.save(apiItem);
		}else {
			ApiItem one = apiItemDao.getOne(apiItem.getId());
			one.setName(apiItem.getName());
			one.setParentId(apiItem.getParentId());
			result = apiItemDao.save(one);
		}
		return result;
	}



}































